/**
 * @file 密码管理器状态管理
 * @description 管理密码管理器的状态和操作
 * @author AI Assistant
 * @version 1.0.0
 * @since 2025-10-22
 */

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { createStorageState } from 'global-state'
import { PASSWORD_MANAGER_CHANNELS } from '~shared/ipc-topic'

interface QueryUserCredentialParams {
  domain?: string
  username?: string
  site_name?: string
  auto_fill_enabled?: boolean
  is_synced?: boolean
  limit?: number
  offset?: number
  sortBy?: 'domain' | 'username' | 'last_used_at' | 'created_at' | 'updated_at'
  sortOrder?: 'asc' | 'desc'
}

interface DecryptedUserCredential {
  _id: string
  id?: number
  domain: string
  site_name?: string | null
  username: string
  password: string
  favicon_url?: string | null
  auto_fill_enabled: boolean
  is_synced: boolean
  server_id?: string | null
  last_used_at?: Date | null
  created_at: Date
  updated_at: Date
}

interface DatabaseResult<T = any> {
  success: boolean
  data?: T
  error?: string
  count?: number
}

/**
 * 密码管理器状态管理
 */
export const usePasswordManagerStore = defineStore('passwordManager', () => {
  // 状态
  const credentials = ref<DecryptedUserCredential[]>([])
  const isLoading = ref(false)
  const settings = createStorageState(
    'passwordManagerSettings',
    {
      enabled: true,
      auto_fill_enabled: true,
      save_prompt_enabled: true,
      sync_enabled: true
    },
    1
  )
  const isEnabled = computed(() => settings.state.enabled)

  // 计算属性
  const hasCredentials = computed(() => credentials.value.length > 0)
  const enabledCredentials = computed(() =>
    credentials.value.filter(cred => cred.auto_fill_enabled)
  )

  /**
   * 调用主进程 IPC
   */
  async function invokeIPC<T = any>(channel: string, ...args: any[]): Promise<DatabaseResult<T>> {
    try {
      return await _pre_.ipcInvoke(channel, ...args)
    } catch (error) {
      console.error(`IPC调用失败 (${channel}):`, error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '操作失败'
      }
    }
  }

  /**
   * 添加凭据
   */
  async function addCredential(input: F2.user.WebCredential): Promise<boolean> {
    const result = await invokeIPC(PASSWORD_MANAGER_CHANNELS.ADD_CREDENTIAL, input)
    if (result.success) {
      await loadCredentials()
    }
    return result.success
  }

  /**
   * 更新凭据
   */
  async function updateCredential(input: F2.user.WebCredential): Promise<boolean> {
    const result = await invokeIPC(PASSWORD_MANAGER_CHANNELS.UPDATE_CREDENTIAL, {
      ...input,
      id: input.credentialId
    })
    if (result.success) {
      await loadCredentials()
    }
    return result.success
  }

  /**
   * 删除凭据
   */
  async function deleteCredential(id: string): Promise<boolean> {
    const result = await invokeIPC(PASSWORD_MANAGER_CHANNELS.DELETE_CREDENTIAL, id)
    if (result.success) {
      credentials.value = credentials.value.filter(cred => cred._id !== id)
    }
    return result.success
  }

  /**
   * 加载凭据列表
   */
  async function loadCredentials(params?: QueryUserCredentialParams): Promise<void> {
    isLoading.value = true
    try {
      const result = await invokeIPC<DecryptedUserCredential[]>(
        PASSWORD_MANAGER_CHANNELS.GET_DECRYPTED_CREDENTIALS,
        params
      )
      if (result.success && result.data) {
        credentials.value = result.data
      }
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取指定域名的凭据
   */
  async function getCredentialsForDomain(domain: string): Promise<DecryptedUserCredential[]> {
    const result = await invokeIPC<DecryptedUserCredential[]>(
      PASSWORD_MANAGER_CHANNELS.GET_DECRYPTED_CREDENTIALS,
      {
        domain,
        auto_fill_enabled: true,
        sortBy: 'last_used_at',
        sortOrder: 'desc'
      }
    )

    return result.success && result.data ? result.data : []
  }

  /**
   * 更新最后使用时间
   */
  async function updateLastUsed(id: string): Promise<boolean> {
    const result = await invokeIPC(PASSWORD_MANAGER_CHANNELS.UPDATE_LAST_USED, id)
    return result.success
  }

  /**
   * 生成安全密码
   */
  async function generatePassword(length = 16): Promise<string | null> {
    const result = await invokeIPC<string>(PASSWORD_MANAGER_CHANNELS.GENERATE_PASSWORD, length)
    return result.success && result.data ? result.data : null
  }

  /**
   * 检查密码强度
   */
  async function checkPasswordStrength(password: string): Promise<{
    score: number
    level: 'weak' | 'fair' | 'good' | 'strong'
    feedback: string[]
  } | null> {
    const result = await invokeIPC(PASSWORD_MANAGER_CHANNELS.CHECK_PASSWORD_STRENGTH, password)
    return result.success && result.data ? result.data : null
  }

  /**
   * 搜索凭据
   */
  function searchCredentials(query: string): DecryptedUserCredential[] {
    if (!query.trim()) return credentials.value

    const lowerQuery = query.toLowerCase()
    return credentials.value.filter(
      cred =>
        cred.domain.toLowerCase().includes(lowerQuery) ||
        cred.site_name?.toLowerCase().includes(lowerQuery) ||
        cred.username.toLowerCase().includes(lowerQuery)
    )
  }

  /**
   * 同步到云端
   */
  async function syncToCloud(): Promise<{
    success: boolean
    synced?: number
    failed?: number
    error?: string
  }> {
    const result = await invokeIPC<{ synced: number; failed: number }>(
      PASSWORD_MANAGER_CHANNELS.SYNC_TO_CLOUD
    )
    if (result.success && result.data) {
      return { success: true, synced: result.data.synced, failed: result.data.failed }
    }
    return { success: false, error: result.error || '同步到云端失败' }
  }

  /**
   * 从云端同步
   */
  async function syncFromCloud(
    cloudCredentials: F2.user.UserCredential[]
  ): Promise<{ success: boolean; imported?: number; updated?: number; error?: string }> {
    const result = await invokeIPC<{ imported: number; updated: number }>(
      PASSWORD_MANAGER_CHANNELS.SYNC_FROM_CLOUD,
      cloudCredentials
    )
    if (result.success && result.data) {
      await loadCredentials() // 重新加载凭据
      return { success: true, imported: result.data.imported, updated: result.data.updated }
    }
    return { success: false, error: result.error || '从云端同步失败' }
  }

  /**
   * 初始化
   */
  async function initialize(): Promise<void> {
    await loadCredentials()
  }

  return {
    // 状态
    isEnabled,
    settings,
    credentials,
    isLoading,

    // 计算属性
    hasCredentials,
    enabledCredentials,

    // 方法
    addCredential,
    updateCredential,
    deleteCredential,
    loadCredentials,
    getCredentialsForDomain,
    updateLastUsed,
    generatePassword,
    checkPasswordStrength,
    searchCredentials,
    syncToCloud,
    syncFromCloud,
    initialize
  }
})
